import { useEffect,useState } from "react";
import { Link } from "react-router-dom";
import { getStusAsync } from "../redux/slice";
import { useSelector,useDispatch } from "react-redux";
import '../assets/home.css'

function Home() {
  const stuList = useSelector((state)=>state.stuList)
  const dispatch = useDispatch()
  const [searchItem,setSearchItem] = useState({})
  
  
  const handleChange = function(value){
    setSearchItem(value)
  }

  useEffect(()=>{
    if (stuList.length === 0){
      console.log('list:',stuList)
      dispatch(getStusAsync())
    }
  },[stuList,dispatch])

  const tbodyList = stuList.map((stu)=>{
    return (
      <tr key={stu.id}>
        <th>{stu.name}</th>
        <th>{stu.age}</th>
        <th>{stu.email}</th>
        <th>{stu.number}</th>
        <th>{<Link to={`/detail/${stu.id}`}>详情</Link>}</th>
      </tr>
    )
  })

  return ( 
    <div>
      <h1>学生列表</h1>
      <input 
        type="text" 
        className="form-control"
        value={searchItem}
        onChange={handleChange}
        />
        <div>
          <table className="table table-striped table-bordered">
            <thead>
              <tr>
                <th>姓名</th>
                <th>年龄</th>
                <th>邮箱</th>
                <th>联系方式</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {tbodyList}
            </tbody>
          </table>
        </div>
    </div>
   );
}

export default Home;